<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px" :rules="rules" ref="form" :model="crud.order"
                 :disabled="crud.order.orderStatus==='CLOSE'">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编码" label-width="80px">
                <el-input  v-model="crud.order.code" disabled placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期" label-width="80px">
                <el-date-picker
                  v-model="crud.order.busDate"
                  type="date"
                  style="width: 100%;"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商" prop="customerId" label-width="80px">
                <zSelect :value.sync="crud.order.customerId" :showName="crud.order.customerName" @getChange="getInfo" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/basCustomerList"  :params="{isContact:'1,2'}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--              <el-form-item label="单据类型" prop="sourceType">-->
<!--                <el-select v-model="crud.order.sourceType"   style="width: 100%;" :disabled="crud.order.orderStatus==='PASS'" class="edit-input" placeholder="请选择来源类型" >-->
<!--                  <el-option-->
<!--                    v-for="(item,index) in dict.t_mobile_enter_source_type"-->
<!--                    :key="index"-->
<!--                    v-if="item.seq>0"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态" label-width="80px">
                <el-select
                  v-model="crud.order.orderStatus"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="状态"
                  size="small"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="是否追加" prop="isAppend" label-width="80px">
                <el-select
                  v-model="crud.order.isAppend"
                  class="filter-item"
                  clearable
                  :disabled="crud.order.orderStatus==='CLOSE'"
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in  dict.common_yes_or_no"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="采购渠道" prop="buyChannel" label-width="80px">
                  <el-select
                    v-model="crud.order.buyChannel"
                    class="filter-item"
                    clearable
                    placeholder="采购渠道"
                    size="small"
                    :disabled="crud.order.orderStatus==='PASS'"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in  dict.t_buy_order_buy_channel"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value + ''"
                    />
                  </el-select>
                </el-form-item>

            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="入库仓库" label-width="80px" prop="warehouseId">
                <zSelect :value.sync="crud.order.warehouseId"  :showName="crud.order.warehouseName" :label="crud.order.warehouseName" :disabled="$route.params.id!='add'" url="api/dropDown/basWarehouseList" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="采购部门" prop="deptId" label-width="80px">
                <zSelect :value.sync="crud.order.deptId" :showName="crud.order.deptName"  :label="crud.order.deptName" :disabled="crud.order.orderStatus==='PASS'"  url="api/dropDown/childSysDeptList" :params="{deptId:crud.order.deptId}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            </el-row>
           <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="采购人员" label-width="80px">
                <zSelect :value.sync="crud.order.userId" :showName="crud.order.userName" :label="crud.order.userName"  :disabled="crud.order.deptId&&crud.order.orderStatus==='PASS'" url="api/dropDown/sysUserList" :params="{deptId:crud.order.deptId}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
<!--             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--               <el-form-item label="到货日期" prop="acceptDate">-->
<!--                 <el-date-picker-->
<!--                   v-model="crud.order.acceptDate"-->
<!--                   type="date"-->
<!--                   style="width: 100%;"-->
<!--                   :disabled="crud.order.orderStatus==='PASS'"-->
<!--                   default-value-->
<!--                   format="yyyy - MM - dd "-->
<!--                   value-format="yyyy-MM-dd"-->
<!--                   placeholder="选择日期">-->
<!--                 </el-date-picker>-->
<!--               </el-form-item>-->
<!--             </el-col>-->
<!--             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--               <el-form-item label="是否第三方采购" prop="isContact">-->
<!--                 <el-select-->
<!--                   v-model="crud.order.isContact"-->
<!--                   class="filter-item"-->
<!--                   clearable-->
<!--                   placeholder="状态"-->
<!--                   size="small"-->
<!--                   style="width: 100%"-->
<!--                 >-->
<!--                   <el-option-->
<!--                     v-for="item in  dict.common_yes_or_no"-->
<!--                     :key="item.id"-->
<!--                     :label="item.label"-->
<!--                     :value="item.value"-->
<!--                   />-->
<!--                 </el-select>-->
<!--               </el-form-item>-->
<!--             </el-col>-->
<!--             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >-->
<!--               <el-form-item label="默认库位">-->
<!--                 <zSelect :value.sync="crud.order.storehouseId"  :disabled="crud.order.warehouseId&&crud.order.orderStatus==='PASS'" :params="{warehouseId:crud.order.warehouseId}"-->
<!--                          url="api/dropDown/basStorehouseList" >-->
<!--                 </zSelect>-->
<!--               </el-form-item>-->
<!--             </el-col>-->
             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
               <el-form-item label="备注" label-width="80px">
                 <el-input  v-model="crud.order.remark"  :disabled="crud.order.orderStatus==='CLOSE'"  placeholder="请输入"></el-input>
               </el-form-item>
             </el-col>
             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
               <el-form-item label="单据说明" label-width="80px">
                 <el-input  v-model="crud.order.orderRemark"  :disabled="crud.order.orderStatus==='CLOSE'"  placeholder="请输入"></el-input>
               </el-form-item>
             </el-col>
             <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
               <el-form-item label="上架人" multiple prop="groundUserIds" label-width="80px">
                 <zSelect :value.sync="crud.order.groundUserIds" multiple :showName="crud.order.groundUserName" :label="crud.order.groundUserName"  :disabled="crud.order.orderStatus==='CLOSE'" url="api/dropDown/sysUserList"
                          style="width:  100%"/>
               </el-form-item>
             </el-col>
           </el-row>
        </el-form>
      </div>
      <!--   操作栏   -->
      <div >
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          :disabled="crud.order.orderStatus==='CLOSE'"
          type="primary"
          @click="toAdd()"
        >
          新增
        </el-button>
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="success"-->
        <!--          :disabled="crud.selections.length !== 1"-->
        <!--          @click="toDeatil(crud.selections)"-->
        <!--        >修改-->
        <!--        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          :disabled="crud.order.orderStatus==='CLOSE'"
          type="primary"
          @click="submit()"
        >
          保存
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id=='null'"
          :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('PASS',id)"

        >
          <!--        v-permission="permission.pass"-->
          审核
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.doDetailPassOrReject('REJECT',id)"

        >
          <!--        v-permission="permission.reject"-->
          反审
        </el-button>
<!--        <el-button-->
<!--          slot="right"-->
<!--          class="filter-item"-->
<!--          size="mini"-->
<!--          type="success"-->
<!--          :disabled="$route.params.id=='null'"-->
<!--          :loading="crud.passLoading"-->
<!--          @click="crud.doDetailPassOrReject('INVALID',id)"-->

<!--        >-->
<!--          &lt;!&ndash;        v-permission="permission.pass"&ndash;&gt;-->
<!--          作废-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          slot="right"-->
<!--          class="filter-item"-->
<!--          size="mini"-->
<!--          type="info"-->
<!--          :loading="crud.rejectLoading"-->
<!--          :disabled="$route.params.id=='null'"-->
<!--          @click="crud.doDetailPassOrReject('RECOVER',id)"-->

<!--        >-->
<!--          &lt;!&ndash;        v-permission="permission.reject"&ndash;&gt;-->
<!--          取消作废-->
<!--        </el-button>-->
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
        >打印</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
        >打印预览</el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.toPrint(id)"

        >
          <!--        v-permission="permission.reject"-->
          打印预览
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="handleShow"

        >
          <!--        v-permission="permission.reject"-->
          批量新增
        </el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('up')"
        >上一页</el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('down')"
        >下一页</el-button>
      </div>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="wareBuyEnter"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>

      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>
      <!--      :summary-method="crud.getSummaries"-->
      <el-table ref="table" row-class-name="crud.tableRowClassName"
                height="600px"
                :data="crud.data"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                @row-dblclick="switchRowIndex"
                highlight-current-row="highlight-current-row"
                size="small"
                style="width: 100%;"
                :show-summary="true"
                :summary-method="crud.sumRow"
                sortable="custom"
                border
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @sort-change="crud.sortChange"
                @selection-change="crud.selectionChangeHandler"
               >
        <el-table-column :render-header="crud.renderHeader" type="selection"  />
        <el-table-column :render-header="crud.renderHeader" type="index"  label="序号"/>
        <el-table-column

          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" >{{scope.row[`${item.prop}`]}}</span>
              <span v-else-if="item.type == 2" >{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-else-if="item.type == 3" >{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
              <span v-else-if="item.type == 4" >
                <span v-if="item.prop == 'goodsName'" class="tabInput">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.goodsName }}</span>
                  <jtg-select-plus v-else ref="productRef"
                                   v-model="scope.row.goodsId"
                                   :initValue="scope.row.goodsName"
                                   :customerId="crud.order.customerId"
                                   typeName="BUY"
                                   :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                                   :buyChannel="crud.order.buyChannel"
                                   @remoteMethod="getValue($event,scope.$index)"
                                   @input="getInput($event,name,scope.$index)"
                                   @change="crud.productChange($event,scope)"
                                   url="productList"/>
                </span>
                <span v-else-if="item.prop == 'goodsTagName'" class="tabInput">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.goodsTagName }}</span>
                  <zSelect :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" v-else :value.sync="scope.row.goodsTagId" :showName="scope.row.goodsTagName"    @change="crud.setProduct($event,scope,'goodsTagName')" url="api/dropDown/basGoodsTagList"    style="width: 100%;"/>
                </span>
                <span v-else-if="item.prop == 'warehouseName'" class="tabInput">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.warehouseName }}</span>
                  <zSelect :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" v-else v-model="scope.row.warehouseId" class="edit-input"         @change="crud.setProduct($event,scope,'warehouseName')" :value.sync="scope.row.warehouseId" url="api/dropDown/basWarehouseList" />
                </span>
                <span v-else-if="item.prop == 'storehouseName'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.storehouseName }}</span>
                  <zSelect :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" v-else :value.sync="scope.row.storehouseId" @change="crud.setProduct($event,scope,'storehouseName')" :params="{warehouseId:scope.row.warehouseId}"  url="api/dropDown/basStorehouseList"    style="width: 100%;"/>
                </span>
                <span v-else-if="item.prop == 'boxUnitId'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
                  <el-input v-else
                            :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                            @input.native="crud.inuptCount(scope, 'boxNum')"
                            maxlength="12"
                            v-model="scope.row.boxNum"
                            style="width: 45%;float: left">
                    <template slot="append">{{scope.row.boxUnitName}}</template>
                  </el-input>
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
                  <el-input v-else
                            :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                            @input.native="crud.inuptCount(scope, 'mainNum')"
                            maxlength="12"
                            v-model="scope.row.mainNum"
                            style="width: 45%;float: right">
                    <template slot="append">{{scope.row.mainUnitName}}</template>
                  </el-input>
                </span>
                <span v-else-if="item.prop == 'taxPrice'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.taxPrice }}</span>
                  <el-input v-else
                            @input.native="crud.inuptCount(scope, 'taxPrice')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.taxPrice"
                            style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'discountRate'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.discountRate }}</span>
                  <el-input v-else
                            :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                            @input.native="crud.inuptCount(scope, 'discountRate')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.discountRate"
                            style="width: 100%">
                    <template slot="append">
                      %
                    </template>
                  </el-input>
                </span>
                <span v-else-if="item.prop == 'noTaxPrice'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.noTaxPrice }}</span>
                  <el-input v-else
                            :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                            @input.native="crud.inuptCount(scope, 'noTaxPrice')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.noTaxPrice"
                            style="width: 100%">
                  </el-input>
                </span>
                <span v-else-if="item.prop == 'taxBoxPrice'">
                  <span v-if="scope.$index !== rowIndex">{{ scope.row.taxBoxPrice }}</span>
                  <el-input v-else
                            :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                            @input.native="crud.inuptCount(scope, 'taxBoxPrice')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.taxBoxPrice"
                            style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'taxAmount'">
                    <span v-if="scope.$index !== rowIndex">{{ scope.row.taxAmount }}</span>
                                <el-input v-else
                                          :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                                          @input.native="crud.inuptCount(scope, 'taxAmount')"
                                          oninput="value=value.replace(/[^\d^\.]/g,'')"
                                          maxlength="12"
                                          v-model.lazy="scope.row.taxAmount"
                                          style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'producedDate'">
                  <span v-if="scope.$index !== rowIndex"> {{ parseTime(scope.row.producedDate) }}</span>
                  <el-date-picker
                    v-else
                    :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                    v-model="scope.row.producedDate"
                    type="date"
                    size="small"
                    class="date-item"
                    style="width: 100%;"
                    format="yyyy - MM - dd"
                    value-format="yyyy-MM-dd"
                  />
                </span>
                <span v-else-if="item.prop == 'deadlineDate'">
                  <span v-if="scope.$index !== rowIndex"> {{ parseTime(scope.row.deadlineDate) }}</span>
                  <el-date-picker
                    v-else
                    :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                    v-model="scope.row.deadlineDate"
                    type="date"
                    size="small"
                    class="date-item"
                    style="width: 100%;"
                    format="yyyy - MM - dd"
                    value-format="yyyy-MM-dd"
                  />
                </span>
                <span v-else-if="item.prop == 'batchNo'">
                  <span v-if="scope.$index !== rowIndex"> {{ scope.row.batchNo }}</span>
                 <el-input v-else  :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" v-model.lazy="scope.row.batchNo"
                            style="width: 100%"></el-input>
                </span>
                <span v-else-if="item.prop == 'remark'">
                    <span v-if="scope.$index !== rowIndex"> {{ scope.row.remark}}</span>
                    <el-input v-else
                              :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                              v-model.lazy="scope.row.remark"
                               style="width: 100%"></el-input>
                </span>
                <span v-else-if="item.prop == 'oldBoxNum'">
                    <span >{{ scope.row.oldBoxNum }}{{ scope.row.boxUnitName }}</span>
                    <span >{{ scope.row.oldMainNum }}{{ scope.row.mainUnitName }}</span>
                </span>
                <span v-else-if="item.prop == 'oldGoodsCount'">
                    <el-button
                      slot="reference" class="el-icon-delete opration_icon_btn"
                      :disabled="crud.order.orderStatus==='CLOSE'||$route.params.id!='add'"
                      style="border: none;width: auto;height: auto"
                      @click="delAddRow(scope.$index)"></el-button>
                </span>
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <!--      <pagination />-->
      <!--      批量新增-->
      <el-dialog
        title="批量新增"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
         <addBatch :showAddBatchDialog.sync="dialogVisible" :list="crud.data"
                   :params="{customerId:crud.order.customerId,type:crud.order.type==1?'SALE':'SALE_RETURN',}"
                   @change="afterChangeGoods" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import { getCompany } from '@/api/system/company'
import {Notification} from "element-ui";
import crudWareBuyEnter from '@/api/erp/wareBuyEnter'
import addBatch from '@/components/addBatch/addBatch'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import {tablemixins} from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import {salesDetailKey} from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";

// crud交由presenter持有
const defaultCrud = CRUD({ title: '采购入库单明细',name:'wareBuyEnterDetail',
  params() {
    const href = location.href.split('/')
    return {
      id: href[href.length - 1].split('?')[0] == 'add' ? 0 : href[href.length - 1].split('?')[0],  page: 0, size: 999,
      // id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1],  page: 0, size: 999,
    }
  },
  url: 'api/wareBuyEnter/detail',sort:'t.seq,asc', crudMethod: { ...crudWareBuyEnter }})
const defaultForm = { id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null ,idList: []}
export default {
  name: 'wareBuyEnterDetail',
  components: { pagination, crudOperation, rrOperation, udOperation,jtgSelectPlus,addBatch,jPrintConfig,jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), tablemixins,salesDetailKey ],
  dicts: ['common_yes_or_no','common_order_status','t_mobile_enter_source_type','t_buy_order_buy_channel'],

  data() {
    return {
      id: null,
      dialogVisible: false,
      permission: {
        add: ['admin', 'wareBuyEnterDetail:add'],
        edit: ['admin', 'wareBuyEnterDetail:edit'],
        del: ['admin', 'wareBuyEnterDetail:del'],
        import: ['admin', 'wareBuyEnterDetail:import'],
        export: ['admin', 'wareBuyEnterDetail:export'],
        copy: ['admin', 'wareBuyEnterDetail:copy'],
        upload: ['admin', 'wareBuyEnterDetail:upload'],
        download: ['admin', 'wareBuyEnterDetail:download'],
      },
      rules: {
        deptId: [
          { required: true, message: '采购部门不能为空', trigger: 'blur' }
        ],
        acceptDate: [
          { required: true, message: '到货日期不能为空', trigger: 'blur' }
        ],
        sourceType: [
          { required: true, message: '单据类型不能为空', trigger: 'blur' }
        ],
        buyChannel: [
          { required: true, message: '采购渠道不能为空', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '供应商不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '业务员不能为空', trigger: 'blur' }
        ],
        isAppend: [
          { required: true, message: '是否追加不能为空', trigger: 'blur' }
        ],
        isContact: [
          { required: true, message: '是否第三方采购不能为空', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '仓库不能为空', trigger: 'blur' },
          {
            validator(r, v, cb) {
              if (v < 1) {
                return cb('仓库不能为空');
              }
              cb()
            }
            , message: '仓库不能为空', trigger: 'blur'
          }
        ],
      },
      addRowData:{
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      },
      productList:[],
      idDate: null

    }
  },
  watch: {
  },
  destroyed() {
    this.crud.setItemInfo("wareBuyEnterDetail_add")
  },
  created(){
    const data ={
      modelName:'wareBuyEnterDetail',
      url: "api/wareBuyEnter/detail",
      userId:this.$store.state.user.user.userId,
    }
    this.crud.headerInfo = {
      code:'wareBuyEnterDetail',
      userId:this.$store.state.user.user.userId,
      path: "api/wareBuyEnter/detail",
    }
    if(/add$/.test(window.location.href)){
      getHeaderProperties(data).then(res=>{
        this.crud.header = JSON.parse(res.data.header.content)
        this.$forceUpdate()
      }).catch(err=>{console.log(err)})
    }

    if (this.$route.params.id == 'add') {
      if( this.crud.getItemInfo("wareBuyEnterDetail_add")){
        return false
      }
      this.crud.order = {
        id: null,
        code: '',
        busDate:  this.getTime(),
        // createTime: this.getTime(),
        name: '',
        userId: '',
        deptId: null,
        type: null,
        acceptDate: null,
        isContact: null,
        isAppend: 0,
        orderStatus: 'SAVE',
        index: '0',
        customerId:'',
        groundUserIds: null,
        groundUserName: null,
        buyChannel: '1',
        contactName:'',
        contactPhone:'',
        startDate: null,
        endDate: null,
        remark: ''
      }
      // this.crud.data.push(JSON.parse(JSON.stringify(this.addRowData)))
    }
  },
  mounted() {
    if(/add$/.test(window.location.href)){
      // this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
    }else {
      this.idDate = this.$route.query.idDate
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
    }
  },

  activated() {
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name + 'Id', this.$route.params.id)
    if (!this.crud.header) this.getHeader()
    if (id !== this.$route.params.id) {
      if (this.$route.params.id === 'add') {
        // this.$set(this.crud, 'order', Object.assign({}, copyFrom))
        this.crud.order = {
          id: null,
          code: '',
          busDate:  this.getTime(),
          // createTime: this.getTime(),
          name: '',
          userId: '',
          deptId: null,
          type: null,
          acceptDate: null,
          isContact: null,
          isAppend: 0,
          orderStatus: 'SAVE',
          index: '0',
          customerId:'',
          groundUserIds: null,
          groundUserName: null,
          buyChannel: '1',
          contactName:'',
          contactPhone:'',
          startDate: null,
          endDate: null,
          remark: ''
        }
        this.crud.data = []
        // this.$set(this.crud,'data',[])
      } else if (this.$route.params.id.indexOf('copy') !== -1) {
        const copyid = this.$route.params.id.split('=')[1]
        this.crud.toGetCopyInfo(copyid)
      } else {
        this.crud.params.id = this.$route.params.id
        this.crud.refresh()
      }
    }
  },

  beforeUpdate() {
    if (this.$route.params.id != 'add') {
      this.id = this.$route.params.id
      this.query.id = this.id
      this.crud.order.id = this.id
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    handleShow(){
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.dialogVisible = true
      })
    },
    switchRowIndex(row) {
        if (row.index === this.rowIndex) {
          this.rowIndex = -1
          return
        }
        this.rowIndex = row.index
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.crud.data.map(detail=>detail.goodsId)
      let _goods = []
      let result = []
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true
        this.crud.data.push(good)
        // }
      })
      // this.calcuForm()
    },
    handleClose(done) {
      this.dialogVisible =false
    },
    getInfo(e){
      // this.crud.order.warehouseId = e.warehouseId
      this.$set(this.crud.order,'warehouseId',e.warehouseId)
      this.crud.order.warehouseName = e.warehouseName
      this.crud.order.deptId = e.deptId
      // this.crud.order.deptId = e.deptId
      this.crud.order.userId = e.userId
    },
    delAddRow(i){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delRow(i)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else{
        this.crud.delRow(i)
      }
    },
    getValue(e,i){
      console.log('this.crud.data',this.crud.data )
      this.crud.data[i].productName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if(item.existBox === null){
          item.existBox = 0
        }
        if(item.occupyBox === null){
          item.occupyBox = 0
        }
      })
    },
    getInput(e,name,i){
      console.log(',data.goodsName',e,name,i)
      if(this.crud.data){
        if(e){
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= e
        }else{
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= null
        }
      }
    },
    // 保存
    submit(){
      console.log(this.crud.order)
      const ids = []
      this.crud.data.forEach((item,index)=>{
        if (!item.goodsId){
          ids.push(index)
        }
      })
      for(let i=ids.length-1;i>=0;i--){
        this.crud.data.splice(ids[i],1)
      }
      var oDate1 = new Date(this.crud.order.startDate);
      var oDate2 = new Date(this.crud.order.endDate);
      if(oDate1.getTime() > oDate2.getTime()){
        this.$message({
          message: '开始日期不能大于结束日期',
          type: 'warning'
        })
        this.crud.order.startDate = null
        this.crud.order.endDate = null
        return false
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const table_rules = [
          // {name: '数量', value: 'goodsCount'},
          // {name: '采购价', value: 'taxPrice'},
          // {name: '未税单价', value: 'noTaxPrice'},
          // {name: '含税金额', value: 'taxAmount'},
          // {name: '未税金额', value: 'noTaxAmount'}
        ]
        const result = table_rules.some(({name, value}) => {
          const rules = this.$refs.table.data.some((item, index) => {
            if (!this.tableRules((index + 1), name, item[value])) return true
          })
          if (rules) return true
        })
        if (!result) this.save()
      })
    },
    tableRules(index, name, value) {
      if (!value) {
        Notification.error({title: '序号【' + index + '】' + name + '不能为空'})
        return false
      } else return true
    },
    getTime(date = new Date()){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.order.detailList  = this.crud.data
      let params = this.crud.order
      if (this.crud.order.orderStatus !== 'SAVE') {
        params.isEditWithoutReject = 1
      }
      crudWareBuyEnter.add(params).then(res => {
        if(res.success){
          this.crud.order  = res.data
          // this.crud.data = res.data.detailList
          let id=res.data.id
          if(this.$route.params.id == 'add'){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo('wareBuyEnterDetail_add')
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.refresh()
          this.rowIndex = -1
          that.crud.loadingClose()
        }else{
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res)=>{
        that.crud.loadingClose()
      })
    },
    // 新增
    toAdd(){

      if(!this.crud.order.customerId){
        this.$message({
          message: '请先选择供应商',
          type: 'error'
        })
        return false
      }
      if(!this.crud.order.buyChannel){
        this.$message({
          message: '请先选择采购渠道',
          type: 'error'
        })
        return false
      }
      this.crud.data.push({
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null,boxNum:0,mainNum:0,goodsCount:0
      })
    },
    //修改
    toDetail(){
    },
    detailJump(type){
      console.log(this.idList)
      if (this.idList.length){
        if (type ==='up'){
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== 0){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/ware/wareBuyEnterDetail/${this.idList[index-1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
          console.log(this.$route.params.id)
        }else {
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== this.idList.length-1){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/ware/wareBuyEnterDetail/${this.idList[index+1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
          console.log()
        }
      }
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },

  }
}
</script>

<style scoped>
.tabInput{
 display: flex;
  justify-content: left;
  align-items: left
}
.table-img {
  display: inline-block;
  text-align: left;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
